import { ConfigEnv, UserConfig, defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from "path";
import viteCompression from "vite-plugin-compression";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
    	// 获取环境配置文件
	const env = loadEnv(mode, process.cwd());
    const {VITE_APP_ENV, VITE_API_PUBLIC_PATH} = env
    return {
        base: VITE_APP_ENV === "production" ? VITE_API_PUBLIC_PATH : "/",
        plugins: [
            react(),
            createSvgIconsPlugin({
				// 指定需要缓存的图标文件夹
				iconDirs: [path.resolve(process.cwd(), "src/assets/iconsvg")],
				// 指定symbolId格式
				symbolId: "icon-[dir]-[name]",
			}),
            viteCompression({
				// 开启gzip模式
				verbose: true,
				disable: false,
				threshold: 10240 * 50,
				deleteOriginFile: false, // 压缩后是否删除源文件
				algorithm: "gzip",
				ext: ".gz",
			}),
        ],
        resolve: {
			alias: {
				// 设置 `@` 指向 `src` 目录
				"@": path.resolve(__dirname, "./src"),
				"@assets": path.resolve("src/assets"),
				"@comps": path.resolve("src/components"),
				"@utils": path.resolve("src/utils"),
				"@router": path.resolve("src/router"),
				"@store": path.resolve("src/store"),
			},
			extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json"],
		},
        build: {
			// https://blog.csdn.net/lj1530562965/article/details/122231280
			// 混淆器设置
			minify: "terser",
			// 不生成source map文件，默认false
			sourcemap: false,
			// 指定输出路径（相对于项目根目录)，默认dist
			outDir: "reactMap",
			// 指定生成静态资源的存放路径，默认assets
			assetsDir: "assets",
			// chunk大小警告限制，默认500kbs
			chunkSizeWarningLimit: 1500,
			// 是否禁用css拆分(默认true)，设置false时所有CSS将被提取到一个CSS文件中
			cssCodeSplit: true,
			// 简要配置
			terserOptions: {
				compress: {
					// 移除console
					drop_console: true,
					// 移除debugger
					drop_debugger: true,
				},
				// 保留类名
				keep_classnames: true,
				format: {
					// 移除所有的注释
					comments: false,
				},
			},
			// js、css等文件打包到不同文件夹
			// https://rollupjs.org/guide/en/#outputoptions-object
			/* rollupOptions: {
                    output: {
                        chunkFileNames: "assets/js/[name]-[hash].js",
                        entryFileNames: "assets/js/[name]-[hash].js",
                        assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
                    }
                } */
		},
        		// server config
		server: {
			host: "0.0.0.0", // 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
			port: 8082,
			open: true,
			cors: true,
			// https: false,
			proxy: {
				"/dev-api": {
					target: "https://ydast.cn/api", // easymock
					changeOrigin: true,
					// rewrite: path => path.replace(/^\/api/, "")
					rewrite: path => path.replace(new RegExp('^' + env.VITE_API_URL), '')
				}
			}
		},
    }
})
